---
import type { MarkdownHeading } from "astro";
import { widgetManager } from "../../utils/widget-manager";
import type { WidgetComponentConfig } from "../../types/config";

// 动态导入所有可能的组件
import Profile from "./Profile.astro";
import Announcement from "./Announcement.astro";
import Categories from "./Categories.astro";
import Tags from "./Tags.astro";
import TOC from "./TOC.astro";
import MusicPlayer from "./MusicPlayer.svelte";

interface Props {
	class?: string;
	headings?: MarkdownHeading[];
	customComponents?: Record<string, any>; // 允许传入自定义组件
}

const { class: className, headings, customComponents = {} } = Astro.props;

// 获取配置的组件列表
const topComponents = widgetManager.getComponentsByPosition("top");
const stickyComponents = widgetManager.getComponentsByPosition("sticky");

// 扩展的组件映射表，支持自定义组件
const componentMap = {
	profile: Profile,
	announcement: Announcement,
	categories: Categories,
	tags: Tags,
	toc: TOC,
	"music-player": MusicPlayer,
	...customComponents, // 合并自定义组件
};

/**
 * 组件渲染器 - 负责渲染单个组件
 * @param component 组件配置
 * @param index 组件索引
 * @param allComponents 所有组件列表
 */
function createComponentRenderer(component: WidgetComponentConfig, index: number, allComponents: WidgetComponentConfig[]) {
	const ComponentToRender = componentMap[component.type as keyof typeof componentMap];
	
	if (!ComponentToRender) {
		console.warn(`Component type "${component.type}" not found in component map`);
		return null;
	}
	
	// 获取组件的样式和类名
	const componentClass = widgetManager.getComponentClass(component, index);
	const componentStyle = widgetManager.getComponentStyle(component, index);
	
	// 构建组件属性
	const componentProps = {
		class: componentClass,
		style: componentStyle,
		// 特殊处理：TOC组件需要headings属性
		...(component.type === 'toc' && { headings }),
		// 合并自定义属性
		...component.customProps,
	};
	
	return {
		Component: ComponentToRender,
		props: componentProps,
		config: component,
	};
}

/**
 * 渲染组件列表
 * @param components 组件配置列表
 */
function renderComponents(components: WidgetComponentConfig[]) {
	return components
		.map((component, index) => createComponentRenderer(component, index, components))
		.filter(Boolean); // 过滤掉null值
}

// 渲染顶部和粘性组件
const topComponentsToRender = renderComponents(topComponents);
const stickyComponentsToRender = renderComponents(stickyComponents);

// 检查是否有任何组件需要渲染
const hasTopComponents = topComponentsToRender.length > 0;
const hasStickyComponents = stickyComponentsToRender.length > 0;
const hasAnyComponents = hasTopComponents || hasStickyComponents;
---

{hasAnyComponents && (
	<div id="dynamic-sidebar" class:list={[className, "w-full"]} data-widget-manager="true">
		<!-- 顶部固定组件区域 -->
		{hasTopComponents && (
			<div class="sidebar-top-section flex flex-col w-full gap-4 mb-4" data-position="top">
				{topComponentsToRender.map((renderData) => {
					if (!renderData) return null;
					
					const { Component, props, config } = renderData;
					return (
						<div 
							class="widget-container" 
							data-widget-type={config.type}
							data-widget-order={config.order}
							data-widget-position={config.position}
						>
							<Component {...props} />
						</div>
					);
				})}
			</div>
		)}
		
		<!-- 粘性组件区域 -->
		{hasStickyComponents && (
			<div 
				id="sidebar-sticky" 
				class="sidebar-sticky-section transition-all duration-700 flex flex-col w-full gap-4 top-4 sticky top-4" 
				data-position="sticky"
			>
				{stickyComponentsToRender.map((renderData) => {
					if (!renderData) return null;
					
					const { Component, props, config } = renderData;
					return (
						<div 
							class="widget-container" 
							data-widget-type={config.type}
							data-widget-order={config.order}
							data-widget-position={config.position}
						>
							<Component {...props} />
						</div>
					);
				})}
			</div>
		)}
	</div>
)}

<!-- 当没有启用的组件时显示占位符 -->
{!hasAnyComponents && (
	<div class="sidebar-placeholder text-center text-gray-500 dark:text-gray-400 p-4">
		<p>No widgets enabled</p>
		<p class="text-sm">Configure widgets in your config file</p>
	</div>
)}

<!-- 响应式样式 -->
<style>
	/* 基础样式 */
	#dynamic-sidebar {
		--sidebar-gap: 1rem;
		--sidebar-animation-duration: 0.3s;
	}
	
	/* 组件容器样式 */
	.widget-container {
		transition: all var(--sidebar-animation-duration) ease;
	}
	
	/* 响应式断点样式 */
	@media (max-width: 768px) {
		#dynamic-sidebar {
			display: var(--sidebar-mobile-display, block);
		}
		
		.sidebar-top-section,
		.sidebar-sticky-section {
			gap: calc(var(--sidebar-gap) * 0.75);
		}
	}
	
	@media (min-width: 769px) and (max-width: 1024px) {
		#dynamic-sidebar {
			display: var(--sidebar-tablet-display, block);
		}
	}
	
	@media (min-width: 1025px) {
		#dynamic-sidebar {
			display: var(--sidebar-desktop-display, block);
		}
	}
	
	/* 动画效果 */
	.widget-container {
		opacity: 0;
		transform: translateY(20px);
		animation: slideInUp 0.6s ease forwards;
	}
	
	@keyframes slideInUp {
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
	
	/* 占位符样式 */
	.sidebar-placeholder {
		border: 2px dashed currentColor;
		border-radius: 0.5rem;
		opacity: 0.5;
	}
</style>

<!-- 增强的JavaScript功能 -->
<script>
	import { widgetManager } from "../../utils/widget-manager";
	
	/**
	 * 动态侧边栏管理器
	 * 提供更高级的功能，如组件的动态添加/移除、重排序等
	 */
	class DynamicSidebarManager {
		private sidebar: HTMLElement | null;
		private resizeObserver: ResizeObserver | null = null;
		
		constructor() {
			this.sidebar = document.getElementById('dynamic-sidebar');
			this.init();
		}
		
		init() {
			if (!this.sidebar) return;
			
			this.setupResponsiveDisplay();
			this.setupResizeObserver();
			this.setupWidgetInteractions();
			this.applyInitialAnimations();
		}
		
		/**
		 * 设置响应式显示
		 */
		setupResponsiveDisplay() {
			this.updateResponsiveDisplay();
			window.addEventListener('resize', () => this.updateResponsiveDisplay());
		}
		
		/**
		 * 更新响应式显示
		 */
		updateResponsiveDisplay() {
			if (!this.sidebar) return;
			
			const breakpoints = widgetManager.getBreakpoints();
			const width = window.innerWidth;
			
			let deviceType: 'mobile' | 'tablet' | 'desktop';
			if (width < breakpoints.mobile) {
				deviceType = 'mobile';
			} else if (width < breakpoints.tablet) {
				deviceType = 'tablet';
			} else {
				deviceType = 'desktop';
			}
			
			const shouldShow = widgetManager.shouldShowSidebar(deviceType);
			
			this.sidebar.style.setProperty(
				`--sidebar-${deviceType}-display`, 
				shouldShow ? 'block' : 'none'
			);
			
			// 添加设备类型到数据属性
			this.sidebar.setAttribute('data-device-type', deviceType);
		}
		
		/**
		 * 设置尺寸观察器
		 */
		setupResizeObserver() {
			if (!this.sidebar || !window.ResizeObserver) return;
			
			this.resizeObserver = new ResizeObserver((entries) => {
				for (const entry of entries) {
					const { width, height } = entry.contentRect;
					// 可以在这里添加基于尺寸的逻辑
					console.debug(`Sidebar size changed: ${width}x${height}`);
				}
			});
			
			this.resizeObserver.observe(this.sidebar);
		}
		
		/**
		 * 设置组件交互
		 */
		setupWidgetInteractions() {
			if (!this.sidebar) return;
			
			// 为每个组件容器添加交互功能
			const widgetContainers = this.sidebar.querySelectorAll('.widget-container');
			
			widgetContainers.forEach((container) => {
				const widgetType = container.getAttribute('data-widget-type');
				
				// 添加悬停效果
				container.addEventListener('mouseenter', () => {
					container.classList.add('widget-hover');
				});
				
				container.addEventListener('mouseleave', () => {
					container.classList.remove('widget-hover');
				});
				
				// 可以添加更多交互逻辑
				console.debug(`Widget ${widgetType} interaction setup complete`);
			});
		}
		
		/**
		 * 应用初始动画
		 */
		applyInitialAnimations() {
			if (!this.sidebar) return;
			
			const widgetContainers = this.sidebar.querySelectorAll('.widget-container');
			
			widgetContainers.forEach((container, index) => {
				// 应用交错动画延迟
				const delay = index * 100; // 每个组件延迟100ms
				(container as HTMLElement).style.animationDelay = `${delay}ms`;
			});
		}
		
		/**
		 * 销毁管理器
		 */
		destroy() {
			if (this.resizeObserver) {
				this.resizeObserver.disconnect();
				this.resizeObserver = null;
			}
		}
	}
	
	// 初始化动态侧边栏管理器
	const dynamicSidebarManager = new DynamicSidebarManager();
	
	// 清理函数
	window.addEventListener('beforeunload', () => {
		dynamicSidebarManager.destroy();
	});
</script>